package com.unswift.cloud.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.cloud.pojo.vo.BaseVo;
import com.unswift.cloud.pojo.vo.ResponseBody;
import com.unswift.exception.CoreException;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.ObjectUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@ControllerAdvice
@Api(value="全局异常处理，当系统抛出各种异常时的处理方式", author="unswift", date="2023-06-02", version="1.0.0")
public class GlobalExceptionHandle {

	@ApiField("日志对象")
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@ExceptionHandler(CoreException.class)
	@org.springframework.web.bind.annotation.ResponseBody
	@ApiMethod(value="自定义异常拦截，自定义异常指由本框架定义的异常，都必须基础CoreException", params={@ApiField("http请求对象"), @ApiField("http回调对象"), @ApiField("微服务核心异常")}, returns=@ApiField("当异常时返回对象"))
	public ResponseBody<BaseVo> coreExceptionHandle(HttpServletRequest request, HttpServletResponse response, CoreException e){
		logger.error(e.getMessage(), e);
		String contentType = request.getHeader("Content-Type");
		if(ObjectUtils.isNotEmpty(contentType)){
			response.addHeader("Content-Type", contentType);
		}
		return ResponseBody.error(e.getCode(), e.getMessage());
	}
	
	@ExceptionHandler(Exception.class)
	@org.springframework.web.bind.annotation.ResponseBody
	@ApiMethod(value="其它(系统)异常拦截，除自定义异常之外的异常的拦截", params={@ApiField("http请求对象"), @ApiField("http回调对象"), @ApiField("其它异常")}, returns=@ApiField("当异常时返回对象"))
	public ResponseBody<BaseVo> coreExceptionHandle(HttpServletRequest request, HttpServletResponse response, Exception e){
		logger.error(e.getMessage(), e);
		String contentType = request.getHeader("Content-Type");
		if(ObjectUtils.isNotEmpty(contentType)){
			response.addHeader("Content-Type", contentType);
		}
		CoreException coree = ExceptionUtils.message("undefined.exception", e.getMessage());
		return ResponseBody.error(coree.getCode(), coree.getMessage());
	}

}
